package com.xingshang.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Component
public class FileUploadUtil {

    private static final String UPLOAD_URL = "https://sm.ms/api/v2/upload";
    private static final String AUTHORIZATION_HEADER = "2ui13YORtraV6S2bC6Bg2H320VFzL1M4";

    public String uploadFile(MultipartFile file, String newFileName) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return "Error: 文件为空！";
        }

        try {
            // 创建 URL 和 HttpURLConnection
            URL url = new URL(UPLOAD_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
            connection.setRequestProperty("Authorization", AUTHORIZATION_HEADER);
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");

            // 写入文件数据
            try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
                String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
                String lineEnd = "\r\n";
                String twoHyphens = "--";

                // 写入开始的 boundary
                out.writeBytes(twoHyphens + boundary + lineEnd);
                out.writeBytes("Content-Disposition: form-data; name=\"smfile\"; filename=\"" + newFileName + "\"" + lineEnd); // 使用新文件名
                out.writeBytes("Content-Type: " + "application/octet-stream" + lineEnd); // 文件类型
                out.writeBytes(lineEnd);

                // 写入文件内容
                try (InputStream inputStream = file.getInputStream()) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                }

                // 写入结束的 boundary
                out.writeBytes(lineEnd);
                out.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            }

            // 读取响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonNode = mapper.readTree(response.toString());
                String images = jsonNode.path("images").asText();
                String url1 = jsonNode.path("data").path("url").asText();
//                System.out.println("Response: " + response);
//                System.out.println("url1: " + url1);
//                System.out.println("images: " + images);
                // 返回响应结果
                return Objects.equals(images, "") ? url1 : images;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }
}
